package config

import (
	"crypto/tls"
	"fmt"
	"net/smtp"
	"strings"
)

/**
 *
 * @return
 */
func Send() (code, msg string, b bool) {
	return "", "", true
}

func genBody(from, nickname, to, subject, body string) []byte {
	_header := make(map[string]string)
	_header["From"] = nickname + "<" + from + ">"
	_header["To"] = to
	_header["Subject"] = subject
	_header["Content-Type"] = "text/html; charset=UTF-8"

	_body := ""

	for _k, _v := range _header {
		_body += fmt.Sprintf("%s: %s\r\n", _k, _v)
	}

	_body += "\r\n" + body

	return []byte(_body)
}

func SendByTLS(host, port, from, nickname, pass, to, subject, body string) (code, msg string, b bool) {
	_toS := strings.Split(to, ";")
	_bodyS := genBody(from, nickname, to, subject, body)

	return sendByTLS(host, port, from, pass, _toS, _bodyS)
}

func sendByTLS(host, port, from, pass string, to []string, body []byte) (code, msg string, b bool) {
	_tlsConfig := &tls.Config{
		InsecureSkipVerify: false,
		ServerName:         host,
	}

	_conn, _err := tls.Dial("tcp", fmt.Sprintf("%s:%s", host, port), _tlsConfig)
	if nil != _err {
		return "501", "", false
	}
	defer _conn.Close()

	_client, _err := smtp.NewClient(_conn, host)
	if nil != _err {
		return "502", "", false
	}
	defer _client.Quit()

	_auth := smtp.PlainAuth("", from, pass, host)

	if nil != _auth {
		if _ok, _ := _client.Extension("AUTH"); _ok {
			if _err = _client.Auth(_auth); nil != _err {
				return "503", "", false
			}
		}
	}

	if _err = _client.Mail(from); nil != _err {
		return "504", "", false
	}

	for _, _addr := range to {
		if _err = _client.Rcpt(_addr); nil != _err {
			return "505", "", false
		}
	}

	_w, _err := _client.Data()
	if nil != _err {
		return "506", "", false
	}

	_, _err = _w.Write(body)
	if nil != _err {
		return "507", "", false
	}

	_err = _w.Close()
	if nil != _err {
		return "508", "", false
	}

	return "", "", true
}
